<template>
  <!-- 操作日志 -->
  <div class="app-container table-flex-wrapper">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="" prop="roleKey">
        <el-select class="select1" v-model="queryParams.subscribeMethod" placeholder="请选择推送方式" clearable size="small" @change="handleQuery">
          <el-option v-for="dict in methodOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="roleName">
        <el-input class="select1" v-model="queryParams.subscribeNickName" placeholder="模糊搜索推送人名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="" prop="roleName">
        <el-input class="select1" v-model="queryParams.subscribePhone" placeholder="模糊搜索手机号" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" size="mini" @click="handleAdd">新增</el-button>
        <el-button type="primary" size="mini" @click="handleBatchDisable">批量禁用</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" size="mini" :data="subscriberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="sn" label="序号" width="70" type="index" align="center"></el-table-column>
      <el-table-column prop="subscribeNickName" label="推送人名称" align="center"></el-table-column>
      <el-table-column prop="subscribePhone" label="手机号" align="center"></el-table-column>
      <el-table-column prop="subscribeEmail" label="邮箱" align="center"></el-table-column>
      <el-table-column prop="subscribeMethod" label="推送方式" align="center" :formatter="methodFormat"></el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.isValid" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="operate" label="操作" align="center" class-name="fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" class="btn" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" class="btn white" type="primary" @click="deleteInfo(scope.row.subscriberId)" v-hasPermi="['slope:subscriber:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" class="d1" v-loading="addAndUpdateLoading">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px" size="small">
        <el-form-item label="推送人名称" prop="subscribeNickName">
          <el-input v-model="form.subscribeNickName" placeholder="请输入推送人名称" />
        </el-form-item>
        <el-form-item label="推送方式" prop="subscribeMethod">
          <el-select v-model="form.subscribeMethod" placeholder="请选择推送方式" clearable size="small">
            <el-option v-for="dict in methodOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item v-show="form.subscribeMethod!=null && form.subscribeMethod!=2" label="推送人手机号" prop="subscribePhone">
          <el-input  v-model="form.subscribePhone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item  v-show="form.subscribeMethod!=null && form.subscribeMethod!=1" label="推送人邮箱" prop="subscribeEmail">
          <el-input v-model="form.subscribeEmail" placeholder="请输入邮箱地址" />
        </el-form-item>
        <!--<el-form-item label="推送人手机号" prop="subscribePhone">-->
          <!--<el-input  v-model="form.subscribePhone" placeholder="请输入手机号" />-->
        <!--</el-form-item>-->
        <!--<el-form-item label="推送人邮箱" prop="subscribeEmail">-->
          <!--<el-input v-model="form.subscribeEmail" placeholder="请输入邮箱地址" />-->
        <!--</el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('form')" size="small">确 定</el-button>
        <el-button @click="cancel" size="small">取 消</el-button>
      </div>
    </el-dialog>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

  </div>
</template>

<script>
  import { getSubscriber, listSubscriber, addSubscriber, updateSubscriber, delSubscriber, changeStatus, selectedDisable } from "@/api/slope/subscriber";

  export default {
    name: "subscribe",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 角色表格数据
        subscriberList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        // 日期范围
        dateRange: [],
        // 状态数据字典
        statusOptions: [],
        //推送方式
        methodOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          subscribeMethod: '',
          subscribeNickName: '',
          subscribePhone: ''
        },
        // 表单参数
        form: {},
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 表单校验
        rules: {
          subscribeNickName: [{
            required: true,
            message: "用户昵称不能为空",
            trigger: "blur"
          }],
          subscribeMethod: [{
            required: true,
            message: "推送方式不能为空",
            trigger: "blur"
          }],
          subscribePhone: [{
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
          },{
            validator: (rule, value, callback) => {
              let method = this.form.subscribeMethod;
              let phone = this.form.subscribePhone;
              console.log(method, phone);
              if (method == 0 || method == 1 || method == "手机 邮箱" || method == "手机") {
                if (phone == null || phone == '') {
                  callback('手机号不能为空');
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }],
          subscribeEmail: [{
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          },{
            validator: (rule, value, callback) => {
              let method = this.form.subscribeMethod;
              let email = this.form.subscribeEmail;
              console.log(method, email);
              if (method == 0 || method == 2 || method == "手机 邮箱" || method == "邮箱") {
                if (email == null || email == '') {
                  callback('邮箱不能为空');
                } else {
                  callback();
                }
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }]
        },
        // 新增和修改时发送请求的遮罩层
        addAndUpdateLoading: false,
      };
    },
    created() {
	  let self = this;
      self.getList();
      self.getDicts("sys_normal_disable").then(response => {
        self.statusOptions = response.data;
      }).catch((error)=> {
        console.log(error);
      });

      self.getDicts("subscribe_method").then(response => {
        self.methodOptions = response.data;
      }).catch((error)=> {
        console.log(error);
      });
    },
    methods: {
      /**
       * 删除角色管理信息
       * @param id 角色管理id
       */
      deleteInfo(id) {
        let self = this;
         self.$confirm( "确认要删除该条信息吗?", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          })
          .then(function() {
            delSubscriber(id).then((res)=>{
              if(res.code==200){
                self.msgSuccess(res.msg);
                self.getList();
              }else{
                self.msgError(res.msg);
              }
            }).catch(()=>{
              self.getList();
            });;
          })
          .then(() => {
            self.getList();
          })
          .catch(function(e) {

        });
      },
      /** 查询角色列表 */
      getList() {
        let self = this;
        self.loading = true;
        listSubscriber(self.addDateRange(self.queryParams, self.dateRange)).then(response => {
          self.subscriberList = response.rows;
          self.total = response.total;
          self.loading = false;
          console.log(self.subscriberList);
        }).catch((error)=> {
          console.log(error);
        });
      },
      methodFormat(row, column) {
        return this.selectDictLabel(this.methodOptions, row.subscribeMethod);
      },
      /** 搜索按钮操作 */
      handleQuery() {
        let self = this;
        self.loading = true;
        listSubscriber(self.addDateRange(self.queryParams, self.dateRange)).then(response => {
          self.subscriberList = response.rows;
          self.total = response.total;
		      self.loading = false;
		      console.log(self.subscriberList);
	    	}).catch((error)=> {
          console.log(error);
        });
      },
      //取消
      cancel() {
        this.open = false;
        this.reset();
      },
      /** 新增按钮操作 */
      handleAdd() {
        let self = this;
        self.reset();
        this.open = true;
        this.title = "添加推送用户";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        let self = this;
        self.reset();
        const subscriberId = row.subscriberId || self.ids;
        getSubscriber(subscriberId).then(response => {
          if (response.code == 200) {
            self.open = true;
            self.form = response.data;
            // self.form.subscribeMethod =
            //   self.methodOptions[
            //     self.methodOptions.findIndex(item => {
            //       if (item.dictValue == self.form.subscribeMethod) {
            //         return true;
            //       }
            //     })
            //   ].dictLabel;
            self.form.subscribeMethod = String(self.form.subscribeMethod);
            self.rolePopOptions = response.roles;
            self.title = "修改推送用户";
          }
        }).catch((error)=> {
          console.log(error);
        });
      },
      // 表单重置
      reset() {
        this.form = {
          userId: undefined,
          deptId: 103,
          userName: undefined,
          nickName: undefined,
          password: undefined,
          phonenumber: undefined,
          email: undefined,
          sex: undefined,
          status: "0",
          remark: undefined,
          postIds: [],
          roleIds: []
        };
        this.resetForm("form");
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.subscriberId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.isValid === "0" ? "启用" : "停用";
        this.$confirm( "确认要" + text + "吗?", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          })
          .then(function() {
            let data = {"subscriberId":row.subscriberId,"isValid": row.isValid};
            console.log(data);
            return changeStatus(data);
          })
          .then(() => {
            this.msgSuccess(text + "成功");
          })
          .catch(function() {
            if (row.isValid == "0") {
              row.isValid = "1";
            } else {
              row.isValid = "0";
            }
        });
      },
      /** 提交按钮 */
      submitForm(formInfo) {
        let self = this;
        // if(this.form.subscribeMethod==0&&!this.form.subscribePhone&&!this.form.subscribeEmail){
        //   self.msgError("请先填写手机和邮箱！");
        //   return false
        // }else if(this.form.subscribeMethod==1&&!this.form.subscribePhone){
        //   self.msgError("请先填写手机！");
        //   return false
        // }else if(this.form.subscribeMethod==2&&!this.form.subscribeEmail){
        //   self.msgError("请先填写邮箱！");
        //   return false
        // }
        self.$refs[formInfo].validate(valid => {
          self.addAndUpdateLoading = true;
          if (valid) {
            console.log(self.methodOptions);
            if (self.form.subscriberId != undefined) {
              try {
                self.form.subscribeMethod = self.methodOptions[self.methodOptions.findIndex(i=>{
                  if (self.form.subscribeMethod==i.dictLabel) {
                    return true;
                  }
                })].dictValue;
              } catch {
                self.addAndUpdateLoading = false;
              }
              // console.log(self.form.subscribeMethod,self.methodOptions);
              updateSubscriber(self.form).then(response => {
                if (response.code === 200) {
                  self.msgSuccess("修改成功");
                  self.open = false;
                  self.getList();
                } else {
                  self.msgError(response.msg);
                }
                self.addAndUpdateLoading = false;
              }).catch((error)=> {
                console.log(error);
                this.addAndUpdateLoading = false;
              });
            } else {
              addSubscriber(self.form).then(response => {
                if (response.code === 200) {
                  self.msgSuccess("新增成功");
                  self.open = false;
                  self.getList();
                } else {
                  self.msgError(response.msg);
                }
                this.addAndUpdateLoading = false;
              }).catch((error)=> {
                console.log(error);
                this.addAndUpdateLoading = false;
              });
            }
          }
          self.addAndUpdateLoading = false;
        });
      },
      //批量禁用
      handleBatchDisable() {
        let self = this;
        console.log(self.ids);
        selectedDisable(self.ids).then(response => {
          console.log(response);
          if(response.code==200) {
            self.msgSuccess(response.msg);
            self.getList();
          }
        }).catch((error)=> {
          console.log(error);
        });
      }
    }
  };
</script>
<style>
  .select1 {
    width: 180px;
    height: 32px;
  }
</style>
